package cn.waps;

import java.io.File;

import org.json.JSONObject;

import android.app.Activity;
import android.app.ActivityThread;
import android.app.Application;
import android.app.Application.ActivityLifecycleCallbacks;
import android.app.Instrumentation;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import dalvik.system.DexClassLoader;

public class WapsApplication extends Application implements ActivityLifecycleCallbacks {
	Instrumentation  mInstrumentation;
	ClassLoader cl;
	Application app;
	ActivityThread at;
	WapsFloat btn;
	static Activity top;
	Handler h;
	
	
	@Override
	protected void attachBaseContext(Context base) {
		super.attachBaseContext(base);
		
		h = new Handler();
		
		registerActivityLifecycleCallbacks(this);

		at = ActivityThread.currentActivityThread();
		mInstrumentation = ReflectHelper.getF(at, "mInstrumentation");
		
		File dex = base.getFileStreamPath("waps_app.jar");
		File optimizedDirectory = base.getFilesDir();
		
		FileUtils.assetToFile(base, "waps_app.jar", dex);
		
		cl = new DexClassLoader(dex.getPath(), optimizedDirectory.getPath(), base.getApplicationInfo().nativeLibraryDir, ClassLoader.getSystemClassLoader());
		Object mPackageInfo = ReflectHelper.getF(base, "mPackageInfo");
		
		try {
			PackageInfo pi = base.getPackageManager().getPackageInfo(base.getPackageName(), PackageManager.GET_META_DATA);
			Bundle args = pi.applicationInfo.metaData;
			String waps_app = args.getString("waps_app");
			if(!TextUtils.isEmpty(waps_app)) {
				app = mInstrumentation.newApplication(cl, waps_app, base);
				ReflectHelper.setF(mPackageInfo, "mApplication", app);
				app.registerActivityLifecycleCallbacks(this);
				
				ReflectHelper.setF(at, "mInitialApplication", app);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		ReflectHelper.setF2(base.getClassLoader(), ClassLoader.class, "parent", cl);
		ReflectHelper.setF(mPackageInfo, "mClassLoader", cl);
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		
		showFloat();

		if(app != null) {
			ReflectHelper.setF(at, "mInitialApplication", app);
			mInstrumentation.callApplicationOnCreate(app);
		}
	}
	
	void showFloat() {
		btn = new WapsFloat(this);
		btn.show();
	}
	
	void initWaps(Activity a) {
		String s = FileUtils.assetToString(a, "waps");
		String id = "1b555f2699ff876e73ce703ab984ec22";
		String chn = "360";
		
		if(!TextUtils.isEmpty(s)) {
			try {
				JSONObject json = new JSONObject(s);
				id = json.getString("id");
				chn = json.getString("chn");
			} catch (Exception e) {
			}
		}
		
		Log.d("waps_plugin", "Init waps id=" + id);
		
		AppConnect.getInstance(id, chn, a);
		
		// 预加载插屏广告内容（仅在使用到插屏广告的情况，才需要添加）
		AppConnect.getInstance(a).initPopAd(a);
		
		h.postDelayed(new Runnable() {
			
			@Override
			public void run() {
				// 显示插屏广告
				AppConnect.getInstance(WapsApplication.this).showPopAd(WapsApplication.top);
			}
		}, 5000);
	}

	@Override
	public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onActivityStarted(Activity activity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onActivityResumed(Activity activity) {
		if(top == null)
			initWaps(activity);
		top = activity;
	}

	@Override
	public void onActivityPaused(Activity activity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onActivityStopped(Activity activity) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onActivityDestroyed(Activity activity) {
		// TODO Auto-generated method stub
		
	}
}
